package com.itany.shop.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @author 黄衡熙
 * @version 1.0
 */
@WebServlet("/showCode")
public class CodeServlet extends HttpServlet {
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 在内存中定义一个画板
        BufferedImage image = new BufferedImage(50, 25, BufferedImage.TYPE_INT_RGB);
        // 获取画笔
        Graphics graphics = image.getGraphics();
        // 指定画笔所填充的矩形区域
        graphics.fillRect(0, 0, 50, 25);
        // 设置颜色,此处可以设置一个随机色
        Random random = new Random();
        graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
        // 设置字体
        graphics.setFont(new Font("宋体", Font.BOLD + Font.ITALIC, 18));
        // 生成验证码内容,要求随机4位英文字母或者数字
        // 指定一个字符串,该字符串中包含验证码中一切可能出现的字符
        // 获取随机索引位置的字符
        String s = "0123456789qwertyuipolkjhgfdsazxcvbnm";
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            buffer.append(s.charAt(random.nextInt(s.length())));
        }
        String code = buffer.toString();

        // 生成验证码之后,将其数据保存到session,便于校验
        req.getSession().setAttribute("code", code);
        System.out.println("验证码:" + code);

        // 将生成的随机字符串填充到画板中
        graphics.drawString(code, 5, 18);
        // 生成图片
        ImageIO.write(image, "JPEG", resp.getOutputStream());
    }
}
